<template>
    <div>
        <!-- 条件查询 -->
        <el-form :inline="true" :model="searchMap" style="margin: 20px 0;" ref="searchFormRef">
            <el-form-item prop="name" style="width:200px">
                <el-input v-model="searchMap.name" aria-placeholder="根据姓名查询"></el-input>
            </el-form-item>
            <el-form-item prop="direction" style="width:200px">
                <el-select v-model="searchMap.direction" placeholder="根据学习方向查询">
                    <el-option v-for="options in directionOPtions" :label="options.name" :value="options._id"
                        :key="options._id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="class" style="width:200px">
                <el-select v-model="searchMap.class" placeholder="根据班级查询">
                    <el-option v-for="options in classOptions" :label="options.classname" :value="options._id"
                        :key="options._id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="teacher_id" style="width:200px">
                <el-select v-model="searchMap.teacher_id" placeholder="根据授课教师查询">
                    <el-option v-for="options in teacherOPtions" :label="options.name" :value="options._id"
                        :key="options._id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="manage_id" style="width:200px">
                <el-select v-model="searchMap.manage_id" placeholder="根据学管查询">
                    <el-option v-for="options in manageOptions" :label="options.name" :value="options._id"
                        :key="options._id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="getStudentList()">查询</el-button>
                <el-button @click="resetForm(searchFormRef)">重置</el-button>
                <el-button type="primary" @click="handleAdd">添加学生</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="students" :border="true" style="width: 100% ; height: 500px;">
            <el-table-column type="expand">
                <template #default="props">
                    <div m="4">
                        <p m="t-0 b-2">姓名: {{ props.row.name }}</p>
                        <p m="t-0 b-2">性别: {{ dataFilter(props.row.gender, genderOPtions) }}</p>
                        <p m="t-0 b-2">学校: {{ props.row.school }}</p>
                        <p m="t-0 b-2">专业: {{ props.row.major }}</p>
                        <p m="t-0 b-2">年级: {{ dataFilter(props.row.grade, gradeOPtions) }}</p>
                        <p m="t-0 b-2">学历: {{ dataFilter(props.row.education, educationOPtions) }}</p>
                        <p m="t-0 b-2">学习方向: {{ dataFilter(props.row.direction, directionOPtions) }}</p>
                        <p m="t-0 b-2">身份号码: {{ props.row.id_number }}</p>
                        <p m="t-0 b-2">电话号码: {{ props.row.phone }}</p>
                        <p m="t-0 b-2">家长姓名: {{ props.row.parent }}</p>
                        <p m="t-0 b-2">家长联系电话: {{ props.row.parent_phone }}</p>
                        <p m="t-0 b-2">家庭住址: {{ props.row.address }}</p>
                        <p m="t-0 b-2">QQ号码: {{ props.row.qq }}</p>
                        <p m="t-0 b-2">所在班级: {{ ClassFilter(props.row.class, classOptions) }}</p>
                        <p m="t-0 b-2">入学时间: {{ props.row.admission_date }}</p>
                        <p m="t-0 b-2">授课教师: {{ dataFilter(props.row.teacher_id, teacherOPtions) }}</p>
                        <p m="t-0 b-2">学管: {{ dataFilter(props.row.manager_id, manageOptions) }}</p>
                        <p m="t-0 b-2">照片:
                            <el-image 
                            v-for="(item,index) in props.row.pictures "
                            style="width: 200px; height: 200px" :key="index" :src="baseApi + '/upload/' +item"  :max-scale="7"
                                :min-scale="0.2" :preview-src-list="getSrcList(props.row.pictures)":initial-index="0"
                                fit="cover" />
                        </p>
                        <p m="t-0 b-2">备注信息: 
                            <span v-html="props.row.note"></span>
                           </p>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="序号" type="index" width="80px" />
            <el-table-column label="学生姓名" prop="name" width="100px" />
            <el-table-column label="性别" prop="gender" width="80px">
                <template #default="scope">
                    {{ dataFilter(scope.row.gender, genderOPtions) }}
                </template>
            </el-table-column>
            <el-table-column label="学习方向" prop="direction">
                <template #default="scope">
                    {{ dataFilter(scope.row.direction, directionOPtions) }}
                </template>
            </el-table-column>
            <el-table-column label="电话号码" prop="phone" />
            <el-table-column label="所在班级" prop="class">
                <template #default="scope">
                    {{ ClassFilter(scope.row.class, classOptions) }}
                </template>
            </el-table-column>
            <el-table-column label="授课教师" prop="teacher_id">
                <template #default="scope">
                    {{ dataFilter(scope.row.teacher_id, teacherOPtions) }}
                </template>
            </el-table-column>
            <el-table-column label="学管" prop="manager_id">
                <template #default="scope">
                    {{ dataFilter(scope.row.manager_id, manageOptions) }}
                </template>
            </el-table-column>
            <el-table-column label="入学时间" prop="admission_date" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.row._id)">
                        修改
                    </el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row._id)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />

    </div>
</template>

<script setup lang="ts">
import type { studentInfoData } from '@/api/student/type'
import { onMounted, ref } from 'vue'
// 引入学生小仓库
import useStudentStore from '@/store/modules/student'
import type { roleInforDate } from '@/api/role/type'
import type { userInfoData } from '@/api/user/type'
import useRoleStore from '@/store/modules/role';
import useUserStore from '@/store/modules/user';
import useClassStore from '@/store/modules/class'
import type { classInfoData } from '@/api/class/type'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
const studentStore = useStudentStore()
const students = ref<studentInfoData[]>([])

const baseApi = import.meta.env.VITE_APP_BASE_API
const getSrcList = (imgList:string[])=>{
    return imgList.map(item=>baseApi +'/upload/' + item)
}
console.log('getSrcList',getSrcList);

const searchFormRef = ref<FormInstance>()
// 重置表单
const resetForm = (FormEl: FormInstance | undefined) => {
    if (!FormEl) return
    FormEl.resetFields()
    getStudentList()
}
// 条件查询回掉函数
const handleEdit = (_id: string) => {
$router.push(`/student/update/${_id}`)
}
const handleDelete = (_id: string) => {
ElMessageBox.confirm(
      '确定要删除此条数据吗？',
       'Warning', {
    // if you want to disable its autofocus
    // autofocus: false,，
    confirmButtonText: '确定',
    cancelButtonText:'取消',
    type:"warning"  
   })
   .then(()=>{
    studentStore.deleteStudent(_id).then((_response)=>{
       
      ElMessage({
        type:"success",
        message:"删除成功",
      });
       getStudentList()
    })
    .catch(()=>{})
   })
}
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const handleSizeChange = (val: number) => {
    pageSize.value = val
    getStudentList()
}
const handleCurrentChange = (val: number) => {
    currentPage.value = val
    getStudentList()
}
const searchMap = ref({
    name: '',
    direction: '',
    teacher_id: '',
    manage_id: '',
    class: ''
})
const getStudentList = () => {
    studentStore.getStudentList({
        page: currentPage.value,
        size: pageSize.value,
        searchMap: searchMap.value,
    }).then((respon) => {
        // @ts-ignore
        students.value = studentStore.students;
        total.value = respon?.total as number
    })
}
// 格式化
const roleStore = useRoleStore()
const userStore = useUserStore()
const classstore = useClassStore()
// 角色数组
const roleOptions = ref<roleInforDate[]>([]);
// 用户数组
const userOptions = ref<userInfoData[]>([]);
// 班级数组
const classOptions = ref<classInfoData[]>([])
// 教师id
const teacher_role_id = ref('');
// 学管id
const manager_role_id = ref('');
// 教师数组
const teacherOPtions = ref<userInfoData[]>([]);
// 学管数组
const manageOptions = ref<userInfoData[]>([]);
// 性别/年纪/学历/学习方向数据类型
interface filterData {
    _id: string,
    name: string
}
// 性别数据列表
const genderOPtions = ref<filterData[]>([
    { _id: '0', name: '男' },
    { _id: '1', name: '女' }
])
// 年祭数据列表
const gradeOPtions = ref<filterData[]>([
    { _id: '1', name: '大一' },
    { _id: '2', name: '大二' },
    { _id: '3', name: '大三' },
    { _id: '4', name: '大四' },
    { _id: '5', name: '在读研究生' },
])
// 学历数据列表
const educationOPtions = ref<filterData[]>([
    { _id: '1', name: '专科' },
    { _id: '2', name: '本科' },
    { _id: '3', name: '硕士' },
    { _id: '4', name: '社会' },
])
// 学习方向数据列表
const directionOPtions = ref<filterData[]>([
    { _id: '1', name: 'web前端' },
    { _id: '2', name: 'Java' },
    { _id: '3', name: 'C/C++' },
    { _id: '4', name: '直播电商' },
    { _id: '5', name: '少儿编程' },
    { _id: '6', name: '嵌入式' },
    { _id: '7', name: '导弹维修' },
])
// 获取班级列表
const getClassList = () => {
    return new Promise((resolve, _reject) => {
        if (classstore.classes && classstore.classes.length) {
            classOptions.value = classstore.classes;

            resolve(true)
        } else {

            classstore.getClassAll().then(() => {
                // @ts-ignore
                classOptions.value = classstore.classes;

                resolve(true)
            })
        }
    })
}
// 获取角色数组
const getRoleList = () => {
    return new Promise((resolve, _reject) => {
        if (roleStore.roles && roleStore.roles.length) {
            roleOptions.value = roleStore.roles;
            roleOptions.value.forEach((item) => {
                if (item.name == "教师") {


                    teacher_role_id.value = item._id as string

                } else if (item.name == "学管") {
                    manager_role_id.value = item._id as string

                }

            });
            resolve(true)
        } else {

            roleStore.getRoleList().then(() => {
                // @ts-ignore
                roleOptions.value = roleStore.roles;
                roleOptions.value.forEach((item) => {
                    if (item.name == "教师") {
                        teacher_role_id.value = item._id as string
                    } else if (item.name == "学管") {
                        manager_role_id.value = item._id as string
                    }
                })
                resolve(true)
            })
        }
    })
}
// 获取用户数组
const getUserList = () => {

    return new Promise((resolve, _reject) => {

        if (userStore.users && userStore.users.length) {
            userOptions.value = userStore.users

            userOptions.value.forEach((item) => {
                if (item.role_id == teacher_role_id.value) {
                    teacherOPtions.value.push(item);
                } else if (item.role_id == manager_role_id.value) {
                    manageOptions.value.push(item)
                }
            })
            resolve(true)
        } else {
            userStore.getUserAll().then(() => {
                userOptions.value = userStore.users
                userOptions.value.forEach((item) => {

                    if (item.role_id == teacher_role_id.value) {
                        teacherOPtions.value.push(item);
                        console.log('userOptions.value', teacherOPtions.value);
                    } else if (item.role_id == manager_role_id.value) {
                        manageOptions.value.push(item)
                    }
                })
            })
            resolve(true)
        }
    })
}
// 格式化数据
const dataFilter = (_id: string, options: any) => {
    // @ts-ignore
    const obj = options.find(item => item._id == _id)
    return obj ? obj.name : ''
}
// 格式化班级数据
const ClassFilter = (_id: string, options: any) => {
    // @ts-ignore
    const obj = options.find(item => item._id == _id)
    return obj ? obj.classname : ''
}
import { useRouter } from 'vue-router';
const $router = useRouter()
// 跳转到添加/编辑学生组件
const handleAdd = () => {
    $router.push("/student/update/-1");
}

onMounted(() => {
    getRoleList().then(() => {
        getUserList().then(() => {
            getClassList().then(() => {
                getStudentList()
            })
        })
    })
})
</script>

<style scoped></style>